from app01.Baseview import BasedAPIView
from app01.models import Port, NetDevice
from django.core.paginator import Paginator
from django.db.models import Q


class PortsAPI(BasedAPIView):
    def get_page_all(self, request):
        pageIndex = int(request.GET.get('pageIndex', 1))
        pageSize = int(request.GET.get('pageSize', 10))
        port_name = request.GET.get('name', None)

        query = Q()
        if port_name:
            query = query & Q(name__icontains=port_name)

        try:
            data = Port.objects.filter(query).order_by('-id')
            page = Paginator(data, pageSize)
            resl = []
            for item in list(page.page(pageIndex)):
                try:
                    device_info = NetDevice.objects.get(id=item.device.id)
                    data_dic = {
                        'id': item.id,
                        'name': item.name,
                        'status': item.status,
                        'device': {
                            'device_name': device_info.name,
                            'device': device_info.device_type,
                            'ipaddress': device_info.ipaddress,
                            'status': device_info.status
                        }
                    }
                    resl.append(data_dic)
                except Exception:
                    return super().error(msg='设备信息不存在')
            return super().success(data={
                    'pageIndex': pageIndex,
                    'pageSize': pageSize,
                    'total': page.count,
                    'data': resl
                })
        except:
            return super().error(msg="查询不存在")
